package vn.com.fsoft.model.dao.impl;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import vn.com.fsoft.model.dao.IGovOfficeRegionDAO;
import vn.com.fsoft.model.entities.GovOfficeRegion;
import vn.com.fsoft.utility.HibernateUtils;

public class GovOfficeRegionDAO extends HibernateUtils implements IGovOfficeRegionDAO {
	private static String TABLENAME = "GovOfficeRegion";
	private Session session;
	private static int totalPage;
	public GovOfficeRegionDAO() {
		super();
		this.session = getSessionFactory().openSession();
	}
	
	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GovOfficeRegion> getAllGovOffice(int page, int recordPerPage) {
		// TODO Auto-generated method stub
		List<GovOfficeRegion> allGov = new ArrayList<GovOfficeRegion>(0);
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Query query = session.createQuery("FROM " + TABLENAME);
			int mod = query.list().size()%recordPerPage;
			int numberOfPage = query.list().size()/recordPerPage;
			if(mod!=0){
				numberOfPage = numberOfPage+1;
			}
			this.setTotalPage(numberOfPage);
			query.setFirstResult(recordPerPage*(page-1));
			query.setMaxResults(recordPerPage);
			allGov = query.list();
			session.flush();
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		}
		return allGov;

	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		GovOfficeRegionDAO.totalPage = totalPage;
	}

	

/*	public static void main(String[] args) {
		GovOfficeRegionDAO govDAO = new GovOfficeRegionDAO();
		List<GovOfficeRegion> govs = govDAO.getAllGovOffice();
		Set<County> counties = govs.get(0).getCounties();
		Iterator<County> iterator;
		iterator = counties.iterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next().getCountyName());
		}
		
	}*/

}
